package io.chenglicun.modules.old.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import io.chenglicun.common.service.impl.CrudServiceImpl;
import io.chenglicun.common.constant.Constant;
import io.chenglicun.common.utils.ConvertUtils;
import io.chenglicun.modules.old.dao.OldDepartsDao;
import io.chenglicun.modules.old.dto.OldDepartsDTO;
import io.chenglicun.modules.old.entity.OldDepartsEntity;
import io.chenglicun.modules.old.service.OldDepartsService;
import io.chenglicun.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 村民信息
 *
 * @author HB 137664951@qq.com
 * @since 1.0 2023-11-29
 */
@Service
public class OldDepartsServiceImpl extends CrudServiceImpl<OldDepartsDao, OldDepartsEntity, OldDepartsDTO> implements OldDepartsService {

    @Override
    public QueryWrapper<OldDepartsEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<OldDepartsEntity> wrapper = new QueryWrapper<>();

        Object pid = params.get("pid");
        if (ObjectUtil.isNotEmpty(pid)) {
            wrapper.lambda().eq(OldDepartsEntity::getPid, pid);
        } else {
            List<OldDepartsDTO> dtoList1 = this.getByPids(0L);
            List<OldDepartsDTO> dtoList2 = this.getByPids(dtoList1.stream().map(OldDepartsDTO::getId).toArray(Long[]::new));
            List<OldDepartsEntity> entities = baseDao.selectList(new QueryWrapper<OldDepartsEntity>()
                    .select("max(id) as id").lambda()
                    .in(OldDepartsEntity::getPid, dtoList2.stream().map(OldDepartsDTO::getId).collect(Collectors.toList()))
                    .groupBy(OldDepartsEntity::getDepartname)
            );
            wrapper.lambda().in(OldDepartsEntity::getId, entities.stream().map(OldDepartsEntity::getId).collect(Collectors.toList()));
        }
        wrapper.orderByDesc("sort");

        return wrapper;
    }

    @Override
    public List<OldDepartsDTO> getByPids(Long... pids) {
        List<OldDepartsEntity> entities = baseDao.selectList(new QueryWrapper<OldDepartsEntity>().lambda().in(OldDepartsEntity::getPid, Arrays.asList(pids)));

        return ConvertUtils.sourceToTarget(entities, OldDepartsDTO.class);
    }

    @Override
    public Integer getMaxSort() {
        return baseDao.getMaxSort()+1;
    }
}